<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Service for the shifts
 *
 * @category	RedCross
 * @package		Core_Service
 */
class Core_Service_Shift extends RedCross_Service_ServiceAbstract
{

	public function __construct(Core_Gateway_Shift $gateway)
	{
		parent::__construct($gateway, 'Core_Model_Shift');
	}

	public function fetchMembersWithCourses($role_id)
	{
	if (!is_int($role_id)) {
    		throw new RedCross_Service_Exception('The given argument should be an integer');
    	}
		return $this->_gateway->fetchMembersWithCourses($role_id);
	}

	public function create($eventId, array $data)
	{
	    $this->checkAcl('create');

        $from_date = new RedCross_Date($data['from_date'] . ' ' . $data['from_time'] . ':00', RedCross_Date::NO_DATETIME_FMT);
        $to_date = new RedCross_Date($data['to_date'] . ' ' . $data['to_time'] . ':00', RedCross_Date::NO_DATETIME_FMT);

        $shift = new Core_Model_Shift();
        $shift->fromArray($data);

        $shift->event_id = $eventId;

        $created_at = new RedCross_Date();
        $shift->created_at = $created_at->export();

        $shift->from_date = $from_date->export();
        $shift->to_date = $to_date->export();
        $shift->appearance_time = $from_date->export();

        $authService = RedCross_Factory::getService('Core_Service_Auth');
        $user = $authService->getIdentity();
        $shift->manager_member_id = $user->member_id;

		return $this->save($shift);
	}

    public function fetchAll($paginate = false)
    {
        $this->checkAcl('fetchAll');
        return $this->getGateway()->fetchAll($paginate);
    }

	public function fetchAllActive($paginate = false)
	{
        $this->checkAcl('fetchAll');
		return $this->getGateway()->fetchAllActive($paginate);
	}

    public function fetchAllInActive($paginate = false)
	{
        $this->checkAcl('fetchAll');
		return $this->getGateway()->fetchAllInActive($paginate);
	}

    public function fetchAllContainingUnconfirmedShiftNotifications($paginate = false)
	{
        $this->checkAcl('fetchAll');
		return $this->getGateway()->fetchAllContainingUnconfirmedShiftNotifications($paginate);
	}

    public function fetchAllFutureWithoutFilledRoles($paginate = false)
    {
        $this->checkAcl('fetchAll');
        return $this->getGateway()->fetchAllFutureWithoutFilledRoles($paginate);
    }
    
    public function fetchAllPastWithoutShiftReport($paginate = false)
    {
        $this->checkAcl('fetchAll');
        return $this->getGateway()->fetchAllPastWithoutShiftReport($paginate);
    }

    public function fetchAllWithUnconfirmedShiftReport($paginate = false)
    {
        $this->checkAcl('fetchAll');
        return $this->getGateway()->fetchAllWithUnconfirmedShiftReport($paginate);
    }

	public function fetchByIdIncludingMembers($id)
	{
	    return $this->getGateway()->fetchByIdIncludingMembers($id);
	}

    public function fetchAllUnconfirmedForMember($memberId) {
        return $this->_gateway->fetchAllUnconfirmedForMember($memberId);
    }
    
    public function fetchAllVisibleForMember($member_id, $data = null, $paginate = false)
    {
    	return $this->_gateway->fetchAllVisibleForMember($member_id, $data, $paginate);
    }

    public function fetchAllMissingShiftReportsForMember($memberId) {
        return $this->_gateway->fetchAllMissingShiftReportsForMember($memberId);
    }
    
    public function fetchByEventId($eventId)
    {
	return $this->_gateway->fetchByEventId($eventId);
    }

    public function submitShiftReport($data, $shift, $member_id = null)
    {
        $newShiftReport = is_null($shift->shift_report_id); 
    	if ($newShiftReport)
    	{
    		$shiftReport = new RedCross_Gateway_Base_ShiftReport();
    		$shift->ShiftReport = $shiftReport;
    	} else {
    		$shiftReport = $shift->ShiftReport;
    		if ((bool)$shiftReport->approved)
    		{
    			throw new RedCross_Exception('Rapporten er godkjent og kan ikke endres');
    		}
    	}
    	
    	$replacements = array();
    	foreach ($data as $key => $value)
    	{
    		$keyParts = explode(Core_Form_Shift_Report::REPLACEMENT_EXPLODE_KEY, $key);
    		if ($keyParts[0] === Core_Form_Shift_Report::REPLACEMENT_PREFIX)
    		{
    			$value_to_be_added = (int)$value == -1 ? null : $value; 
    			$replacements[$keyParts[1]] = $value_to_be_added;
    		}
    	}
    	//Update roles with who attended
    	foreach ($shift->Roles as $role) {
    		if (array_key_exists($role->id, $replacements)) {
    			$role->attended_member_id = $replacements[$role->id];
    		}
    	}
    	
    	//Make shift report
    	$date = new RedCross_Date();
    	$dateStr = $date->export();
    	
    	$shiftReport->report = $data['report'];
    	$shiftReport->equipment_list = $data['equipment_list'];
    	$shiftReport->injuries= $data['injuries'];
    	if (!$newShiftReport && is_null($member_id))
    	{
    		//If we are editing an existing shift report and the member_id parameter is
    		//not set, use the member_id the shiftreport already has (this happens when
    		//the admin edits a shift report so that it's not HIS member_id that is set, 
    		//but the original shift leader)
    		$member_id = $shiftReport->member_id;
    	}
    	$shiftReport->member_id = $member_id;
    	$shiftReport->created_at = $dateStr;

    	return $this->save($shift) != false;
    }
    
    public function fetchByIdJoinOnShiftReportShiftRolesRolesAndMember($shift_id)
    {
    	return $this->_gateway->fetchByIdJoinOnShiftReportShiftRolesRolesAndMember($shift_id);
    }
    
    public function approveShiftReport($shift)
    {
		$report = $shift->ShiftReport;
		if (is_null($report))
		{
			throw new RedCross_Exception_NotFound('Rapport for vakt ikke funnet');
		}
		$report->approved = 1;
		return $this->save($shift) != false;
    }
    
    public function fetchFutureShifts($offset = null, $limit = null, $memberId = null)
    {
	return $this->getGateway()->fetchFutureShifts($offset, $limit, $memberId);
    }
    
    public function fetchPastShifts($offset = null, $limit = null, $memberId = null)
    {
	return $this->getGateway()->fetchPastShifts($offset, $limit, $memberId);
    }

    public function fetchByIdForViewShift($shiftId)
    {
        return $this->getGateway()->fetchByIdForViewShift($shiftId);
    }

    public function fetchByIdForEditShift($shiftId)
    {
        return $this->getGateway()->fetchByIdForEditShift($shiftId);
    }
    
}
